using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Lilium.Web.Mvc.AjaxControlToolkit;
using System.Text.RegularExpressions;
using System.Xml;

namespace Samples.Controllers
{
	public class CascadingDropDownController: Controller
	{
		/// <summary>
		/// Helper web service method
		/// </summary>
		/// <param name="knownCategoryValues">private storage format string</param>
		/// <param name="category">category of DropDownList to populate</param>
		/// <returns>list of content items</returns>
		public ActionResult GetDropDownContents(CascadingDropDownContentRequest request)
		{
			if (request == null)
				throw new ArgumentNullException("request");

			var knownCategoryValuesDictionary = CascadingDropDownExtender.ParseKnownCategoryValuesString(request.KnownCategoryValues);
			var result = CascadingDropDownExtender.CreateCascadingDropDownList(Document, Hierarchy, knownCategoryValuesDictionary, request.Category, InputValidationRegex);
			return Json(result);
		}

		public ActionResult Index(string make, string model, string color)
		{
			// Output result string based on which values are specified

			if (Request.HttpMethod != "GET" || Request.IsAjaxRequest())
			{
				if (string.IsNullOrEmpty(make))
				{
					ViewData["ResponseText"] = "Please select a make.";
				}
				else if (string.IsNullOrEmpty(model))
				{
					ViewData["ResponseText"] = "Please select a model.";
				}
				else if (string.IsNullOrEmpty(color))
				{
					ViewData["ResponseText"] = "Please select a color.";
				}
				else
				{
					ViewData["ResponseText"] = string.Format("You have chosen a {0} {1} {2}. Nice car!", color, make, model);
				}
			}
			else
				ViewData["ResponseText"] = "[No response provided yet]";

			if (Request.IsAjaxRequest())
			{
				return PartialView("Response");
			}
			else
				return View();
		}

		// Member variables
		private static XmlDocument _document;
		private static Regex _inputValidationRegex;
		private static object _lock = new object();

		// we make these public statics just so we can call them from externally for the
		// page method call
		public static XmlDocument Document
		{
			get
			{
				lock (_lock)
				{
					if (_document == null)
					{
						// Read XML data from disk
						_document = new XmlDocument();
						_document.Load(global::System.Web.HttpContext.Current.Server.MapPath("~/Content/CarsService.xml"));
					}
				}
				return _document;
			}
		}

		public static string[] Hierarchy
		{
			get { return new string[] { "make", "model" }; }
		}

		public static Regex InputValidationRegex
		{
			get
			{
				lock (_lock)
				{
					if (null == _inputValidationRegex)
					{
						_inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
					}
				}
				return _inputValidationRegex;
			}
		}
	}
}
